package com.kgc.warehouse.bussness.controller;

import com.kgc.warehouse.system.common.CodeMsg;
import com.kgc.warehouse.system.common.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {
    @Value("${warehouse.path}")
    private String basePath;

    @RequestMapping("uploadFile")
    public Map<String,Object> uploadFile(MultipartFile file){
        //得到文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //防止文件名重复造成覆盖
        String fileName = UUID.randomUUID().toString()+ suffix;
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("path", fileName);
        System.out.println("map = " + map);
        return map;
    }

    @RequestMapping("showImageByPath")
    public void showImageByPath(String path, HttpServletResponse response){
        try {
            //通过输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+path));
            //通过输出流将文件写回浏览器显示图片
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应格式
            response.setContentType("image/jpeg");

            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭流
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
